package cn.flying.cloud.auth.security.handler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

import cn.flying.cloud.auth.security.details.UserDetail;
import cn.flying.cloud.auth.security.log.LoginLogHandler;
import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.Rt;

/**
 * 登出成功处理类
 *
 * @author: admin
 * @date: 2023年05月27日 10:47
 * @version: 1.0
 */
@Component
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private LoginLogHandler loginLogHandler;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取当登录用户信息
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        logger.info("租户【{}】的用户【{}-{}】退出系统登录成功！", userDetail.getTenantId(), userDetail.getUserId(), userDetail.getUsername());

        //保存登录日志
        loginLogHandler.logout(userDetail.getUsername(), userDetail.getTenantId(), Ft.Network.getIpAddress(request));

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(Rt.success(RtCodeEnum.R10006.getDesc(), JSONWriter.Feature.WriteMapNullValue)));
        out.flush();
        out.close();
    }
}
